<template>
  <div class="team-container">
    <!-- 顶部导航栏 -->
    <div class="page-header">
      <div class="back-button" @click="onClickLeft">
        <van-icon name="arrow-left" />
      </div>
      <div class="page-title">我的团队</div>
    </div>
    
    <!-- 团队概览卡片 -->
    <div class="team-overview-card">
      <div class="overview-header">
        <div class="header-left">
          <div class="title">团队概览</div>
          <div class="subtitle">邀请好友加入，共同成长</div>
        </div>
        <div class="header-right">
          <van-icon name="friends-o" size="40" class="team-icon" />
        </div>
      </div>
      
      <div class="overview-stats">
        <div class="stat-item">
          <div class="stat-value">{{ teamOverview.totalMembers || 0 }}</div>
          <div class="stat-label">团队总人数</div>
        </div>
        <div class="stat-item">
          <div class="stat-value">{{ teamOverview.vipMembers || 0 }}</div>
          <div class="stat-label">VIP人数</div>
        </div>
        <div class="stat-item">
          <div class="stat-value">{{ teamOverview.todayInvites || 0 }}</div>
          <div class="stat-label">今日邀请</div>
        </div>
      </div>
      
      <div class="invite-section">
        <div class="invite-code-box">
          <div class="invite-code-label">我的邀请码</div>
          <div class="invite-code">{{ teamOverview.inviteCode || '加载中...' }}</div>
        </div>
        <van-button 
          type="primary" 
          class="share-button" 
          @click="shareInvite"
          :loading="sharing"
        >
          分享邀请
        </van-button>
      </div>
      
      <div class="inviter-info" v-if="teamOverview.inviter">
        <div class="inviter-label">邀请人信息</div>
        <div class="inviter-detail">
          <div class="inviter-avatar">
            <van-image
              round
              width="40"
              height="40"
              :src="teamOverview.inviter.avatar || defaultAvatar"
            />
          </div>
          <div class="inviter-data">
            <div class="inviter-name">{{ teamOverview.inviter.nickname || '未设置昵称' }}</div>
            <div class="inviter-address">{{ formatAddress(teamOverview.inviter.address) }}</div>
          </div>
        </div>
      </div>
    </div>
    
    <!-- 团队成员列表 -->
    <div class="team-members-section">
      <div class="section-header">
        <div class="section-title">团队成员</div>
        <div class="section-filter">
          <van-dropdown-menu>
            <van-dropdown-item v-model="filter.status" :options="statusOptions" />
          </van-dropdown-menu>
        </div>
      </div>
      
      <div class="members-list">
        <van-empty v-if="teamMembers.length === 0" description="暂无团队成员" />
        
        <div class="member-card" v-for="(member, index) in teamMembers" :key="index">
          <div class="member-info">
            <div class="member-avatar">
              <van-image
                round
                width="50"
                height="50"
                :src="member.avatar || defaultAvatar"
              />
              <div class="vip-badge" v-if="member.userLevel > 0">VIP{{ member.userLevel }}</div>
            </div>
            <div class="member-details">
              <div class="member-name">{{ member.userName || '未设置昵称' }}</div>
              <div class="member-address">{{ formatAddress(member.address) }}</div>
              <div class="member-join-date">加入时间：{{ member.createdAt }}</div>
            </div>
          </div>
          <!-- <div class="member-stats">
            <div class="member-stat-item">
              <div class="stat-value">{{ member.invites || 0 }}</div>
              <div class="stat-label">邀请</div>
            </div>
            <div class="member-stat-item">
              <div class="stat-value">{{ member.contribution || 0 }}</div>
              <div class="stat-label">贡献值</div>
            </div>
          </div> -->
        </div>
        
        <div class="load-more" v-if="hasMore">
          <van-button plain type="primary" size="small" @click="loadMore" :loading="loading">
            {{ loading ? '加载中...' : '加载更多' }}
          </van-button>
        </div>
      </div>
    </div>
    
    <!-- 分享弹窗 -->
    <van-share-sheet
      v-model:show="showShare"
      title="分享邀请码"
      :options="shareOptions"
      @select="onShareSelect"
    />
  </div>
</template>

<script setup>
import { ref, reactive, onMounted, watch } from 'vue'
import { useRouter } from 'vue-router'
import { showToast } from 'vant'
import { getTeamOverview, getTeamMembers } from '@/api/team'

const router = useRouter()
// 使用默认头像图标
const defaultAvatar = 'https://img.yzcdn.cn/vant/cat.jpeg'

// 团队概览数据
const teamOverview = ref({
  totalMembers: 0,
  vipMembers: 0,
  todayInvites: 0,
  inviteCode: '',
  inviter: null
})

// 团队成员列表
const teamMembers = ref([])
const pageSize = 10
const currentPage = ref(1)
const total = ref(0)
const hasMore = ref(false)
const loading = ref(false)
const sharing = ref(false)

// 筛选选项
const filter = reactive({
  status: 0
})

const statusOptions = [
  { text: '全部成员', value: 0 },
  { text: '仅VIP成员', value: 1 },
  { text: '今日新增', value: 2 }
]

// 分享相关
const showShare = ref(false)
const shareOptions = [
  { name: '微信', icon: 'wechat' },
  { name: '微信朋友圈', icon: 'wechat-moments' },
  { name: '复制链接', icon: 'link' },
  { name: '二维码', icon: 'qrcode' }
]

// 获取团队概览信息
const fetchTeamOverview = async () => {
  try {
    // 尝试从API获取数据
    const res = await getTeamOverview()
    if (res && res.data) {
      teamOverview.value.totalMembers = res.data.todayCount
      teamOverview.value.todayInvites = res.data.vipCount
      teamOverview.value.totalMembers = res.data.teamCount
      teamOverview.value.inviteCode = res.data.inviteCode
      if(res.data.inviterAddress){
        teamOverview.value.inviter = {
            nickname: res.data.inviterNickname || res.data.inviterAddress,
            address: res.data.inviterAddress
        }
      }
    }
  } catch (error) {
    console.error('获取团队概览失败:', error)
  }
}

// 获取团队成员列表
const fetchTeamMembers = async (page = 1) => {
  if (loading.value) return
  
  loading.value = true
  try {
    const params = {
      page,
      pageSize,
      queryType: filter.status
    }
    
    // 尝试从API获取数据
    const res = await getTeamMembers(params)
    if (res && res.data) {
      if (page === 1) {
        teamMembers.value = res.data.list || []
      } else {
        teamMembers.value = [...teamMembers.value, ...(res.data.list || [])]
      }
      
      total.value = res.data.total || 0
      hasMore.value = teamMembers.value.length < total.value
      currentPage.value = page
    }
  } catch (error) {
    console.error('获取团队成员列表失败:', error)
    showToast('使用模拟数据展示')
  } finally {
    loading.value = false
  }
}

// 加载更多
const loadMore = () => {
  if (hasMore.value && !loading.value) {
    fetchTeamMembers(currentPage.value + 1)
  }
}

// 分享邀请
const shareInvite = () => {
  showShare.value = true
}

// 处理分享选择
const onShareSelect = async (option) => {
  if (!teamOverview.value.inviteCode) {
    showToast('邀请码获取失败，请稍后再试')
    return
  }
  
  sharing.value = true
  try {
    const inviteLink = `https://yourapp.com/register?code=${teamOverview.value.inviteCode}`
    
    if (option.name === '复制链接') {
      // 复制到剪贴板
      await navigator.clipboard.writeText(inviteLink)
      showToast({
        type: 'success',
        message: '邀请链接已复制到剪贴板'
      })
    } else {
    //   // 调用分享API
    //   await shareInviteCode({
    //     code: teamOverview.value.inviteCode,
    //     type: option.name
    //   })
      showToast({
        type: 'success',
        message: '暂未实现'
      })
    }
  } catch (error) {
    console.error('分享失败:', error)
    showToast('分享失败，请稍后再试')
  } finally {
    sharing.value = false
    showShare.value = false
  }
}

// 格式化地址，只显示前6位和后4位
const formatAddress = (address) => {
  if (!address) return ''
  return `${address.substring(0, 6)}...${address.substring(address.length - 4)}`
}

// 格式化日期
const formatDate = (dateString) => {
  if (!dateString) return ''
  const date = new Date(dateString)
  return `${date.getFullYear()}-${String(date.getMonth() + 1).padStart(2, '0')}-${String(date.getDate()).padStart(2, '0')}`
}

// 返回上一页
const onClickLeft = () => {
  router.back()
}

// 监听筛选条件变化
watch(filter, () => {
  currentPage.value = 1
  fetchTeamMembers(1)
})

// 页面加载时获取数据
onMounted(() => {
  fetchTeamOverview()
  fetchTeamMembers()
})
</script>

<style lang="scss" scoped>
.team-container {
  padding: 20px;
  padding-top: 0;
  background-color: #f5f7fa;
  min-height: 100vh;
  
  // 页面头部样式
  .page-header {
    display: flex;
    align-items: center;
    padding: 16px 0;
    position: relative;
    
    .back-button {
      position: absolute;
      left: 10px;
      top: 50%;
      transform: translateY(-50%);
      width: 40px;
      height: 40px;
      display: flex;
      align-items: center;
      justify-content: flex-start;
      
      .van-icon {
        font-size: 20px;
        color: #333;
      }
    }
    
    .page-title {
      width: 100%;
      text-align: center;
      font-size: 18px;
      font-weight: 500;
      color: #333;
    }
  }
  
  // 团队概览卡片样式
  .team-overview-card {
    background: linear-gradient(135deg, #6e8efb, #a777e3);
    border-radius: 16px;
    padding: 20px;
    color: white;
    margin-bottom: 20px;
    box-shadow: 0 4px 12px rgba(0, 0, 0, 0.1);
    
    .overview-header {
      display: flex;
      justify-content: space-between;
      align-items: center;
      margin-bottom: 20px;
      
      .header-left {
        .title {
          font-size: 18px;
          font-weight: bold;
          margin-bottom: 4px;
        }
        
        .subtitle {
          font-size: 12px;
          opacity: 0.8;
        }
      }
      
      .header-right {
        .team-icon {
          color: white;
        }
      }
    }
    
    .overview-stats {
      display: flex;
      justify-content: space-between;
      margin-bottom: 20px;
      
      .stat-item {
        text-align: center;
        flex: 1;
        
        .stat-value {
          font-size: 24px;
          font-weight: bold;
          margin-bottom: 4px;
        }
        
        .stat-label {
          font-size: 12px;
          opacity: 0.8;
        }
      }
    }
    
    .invite-section {
      display: flex;
      align-items: center;
      background-color: rgba(255, 255, 255, 0.2);
      border-radius: 12px;
      padding: 15px;
      margin-bottom: 20px;
      
      .invite-code-box {
        flex: 1;
        
        .invite-code-label {
          font-size: 12px;
          opacity: 0.8;
          margin-bottom: 4px;
        }
        
        .invite-code {
          font-size: 20px;
          font-weight: bold;
          letter-spacing: 2px;
        }
      }
      
      .share-button {
        height: 36px;
        border-radius: 18px;
        font-weight: 500;
      }
    }
    
    .inviter-info {
      background-color: rgba(255, 255, 255, 0.2);
      border-radius: 12px;
      padding: 15px;
      
      .inviter-label {
        font-size: 12px;
        opacity: 0.8;
        margin-bottom: 10px;
      }
      
      .inviter-detail {
        display: flex;
        align-items: center;
        
        .inviter-avatar {
          margin-right: 12px;
        }
        
        .inviter-data {
          .inviter-name {
            font-size: 16px;
            font-weight: 500;
            margin-bottom: 4px;
          }
          
          .inviter-address {
            font-size: 12px;
            opacity: 0.8;
          }
        }
      }
    }
  }
  
  // 团队成员列表样式
  .team-members-section {
    background-color: white;
    border-radius: 16px;
    padding: 20px;
    box-shadow: 0 2px 8px rgba(0, 0, 0, 0.05);
    
    .section-header {
      display: flex;
      justify-content: space-between;
      align-items: center;
      margin-bottom: 20px;
      
      .section-title {
        font-size: 18px;
        font-weight: 500;
        color: #333;
      }
    }
    
    .members-list {
      .member-card {
        background-color: #f9f9f9;
        border-radius: 12px;
        padding: 15px;
        margin-bottom: 15px;
        
        .member-info {
          display: flex;
          margin-bottom: 15px;
          
          .member-avatar {
            position: relative;
            margin-right: 15px;
            
            .vip-badge {
              position: absolute;
              bottom: 0;
              right: 0;
              background-color: #ff9800;
              color: white;
              font-size: 10px;
              font-weight: bold;
              padding: 2px 6px;
              border-radius: 8px;
            }
          }
          
          .member-details {
            flex: 1;
            
            .member-name {
              font-size: 16px;
              font-weight: 500;
              color: #333;
              margin-bottom: 4px;
            }
            
            .member-address {
              font-size: 12px;
              color: #666;
              margin-bottom: 4px;
            }
            
            .member-join-date {
              font-size: 12px;
              color: #999;
            }
          }
        }
        
        .member-stats {
          display: flex;
          border-top: 1px solid #eee;
          padding-top: 15px;
          
          .member-stat-item {
            flex: 1;
            text-align: center;
            
            .stat-value {
              font-size: 18px;
              font-weight: bold;
              color: #333;
              margin-bottom: 4px;
            }
            
            .stat-label {
              font-size: 12px;
              color: #999;
            }
          }
        }
      }
      
      .load-more {
        display: flex;
        justify-content: center;
        margin-top: 20px;
      }
    }
  }
}
</style>